<template>
  <auth-page>
    <div class="container">
      <nav-bar title="WiFi绑定" ref="navBarRef" />
      <block>
        <u--form
          labelPosition="left"
          :model="params"
          :rules="rules"
          ref="addWifiFormRef"
        >
          <u-form-item prop="wifiName" ref="item1">
            <u-input
              :customStyle="btnCustomStyle"
              border="none"
              autoHeight
              count
              type="string"
              :maxlength="32"
              v-model="params.wifiName"
              placeholder="请输入WiFi账号"
            >
              <template slot="suffix">
                <text class="maxInput"> {{ params.wifiName.length }}/32 </text>
              </template>
            </u-input>
            <!--            <u&#45;&#45;textarea></u&#45;&#45;textarea>-->
          </u-form-item>
          <u-form-item prop="password">
            <u-input
              :customStyle="btnCustomStyle"
              border="none"
              autoHeight
              count
              type="string"
              :maxlength="32"
              v-model="params.password"
              placeholder="请输入WiFi密码"
            >
              <template slot="suffix">
                <text class="maxInput"> {{ params.password.length }}/32 </text>
              </template>
            </u-input>
            <!--            <u&#45;&#45;textarea-->
            <!--              autoHeight-->
            <!--              count-->
            <!--              :customStyle="btnCustomStyle"-->
            <!--              border="none"-->
            <!--              :maxlength="32"-->
            <!--              v-model="params.password"-->
            <!--              placeholder="请输入WiFi密码"-->
            <!--            ></u&#45;&#45;textarea>-->
          </u-form-item>
        </u--form>
      </block>
      <div
        class="u-tips-color tips"
        :style="[btnCustomStyle, { backgroundColor: '#f9f9f9' }]"
      >
        <div>注：</div>
        <div>1.绑定WiFi需保证手机已打开WiFi，并已连接上准备绑定的WiFi；</div>
        <div>
          2.如WiFi有设置连接限制，请先取消限制，否则用户扫码无法连接WiFi；
        </div>
        <div>3.保存时会校验WiFi账号是否正确，请准确输入WiFi账号</div>
        <!--        <div>4.新增WiFi需本手机提前连接上需要增加 的WiFi才能连接成功。</div>-->
      </div>
      <div class="footer fix-position flex-align-center">
        <button
          v-if="BIND_PAGE_TYPE.EDIT === pageType"
          class="default-button myWifi"
          @click="handleToWiFiList"
          :style="{
            width: '310rpx',
            border: `1rpx solid #000000`,
            borderColor: themeColor,
            backgroundColor: '#fff',
            color: themeColor,
            borderRadius: '44rpx',
          }"
        >
          我的WiFi
        </button>

        <button
          v-if="BIND_PAGE_TYPE.EDIT === pageType"
          class="default-button getPhone"
          @click="handleValidateWiFi"
          :disabled="disabledInput"
          :style="{
            width: '310rpx',
            borderColor: themeColor,
            backgroundColor: themeColor,
            color: '#fff',
            borderRadius: '44rpx',
            opacity: disabledInput ? 0.3 : 1,
          }"
        >
          保存
        </button>

        <block v-if="BIND_PAGE_TYPE.BINGING === pageType">
          <button
            v-if="wifiEnabled"
            class="default-button getPhone"
            open-type="getPhoneNumber"
            :disabled="disabledInput"
            @getphonenumber="(e) => handleMixinAuth(getPhoneNumber, e)"
            :style="{
              borderColor: themeColor,
              backgroundColor: themeColor,
              color: '#fff',
              borderRadius: '44rpx',
              opacity: disabledInput ? 0.3 : 1,
            }"
          >
            保存
          </button>

          <button
            v-else
            :disabled="disabledInput"
            class="default-button getPhone"
            @click="handleValidateWiFi"
            :style="{
              borderColor: themeColor,
              backgroundColor: themeColor,
              color: '#fff',
              borderRadius: '44rpx',
              opacity: disabledInput ? 0.3 : 1,
            }"
          >
            保存
          </button>
        </block>
      </div>

      <modal
        :showTitle="false"
        :visible.sync="isShowBindBusiness"
        right-btn-text="绑定"
        left-btn-text="取消"
        @confirm="handleBindBusiness"
        @cancel="isShowBindBusiness = false"
        :content-customer-style="{ padding: '35rpx 0' }"
      >
        <div class="business-container">
          <div class="text">{{ bindBusinessTitle }}</div>
          <div v-if="businessList.length > 0" class="text">
            <uni-data-select
              :clear="false"
              v-model="tempShopId"
              :localdata="businessList"
            ></uni-data-select>
          </div>
          <div class="font-red text">
            注：绑定商户后，用户可在商户主页连接wifi
          </div>
        </div>
      </modal>
      <modal
        :show-title="false"
        :visible.sync="isShowTestWiFiFail"
        :left-btn-visible="false"
        @confirm="isShowTestWiFiFail = false"
        :right-btn-visible="false"
        :content-customer-style="{ padding: '35rpx 0' }"
      >
        <div class="business-container">
          <div style="color: #13131380" class="marginBottom-20">
            请连接当前需要绑定的WiFi：<text :style="{ color: themeColor }">{{
              params.wifiName
            }}</text
            >，或检查输入的WiFi账号是否与已连接的WiFi不一致
          </div>
          <button
            @click="isShowTestWiFiFail = false"
            class="default-button getPhone"
            :style="{
              borderColor: themeColor,
              backgroundColor: themeColor,
              color: '#fff',
              borderRadius: '44rpx',
              fontSize: '28rpx',
            }"
          >
            确定
          </button>
        </div>
      </modal>
      <modal
        :visible.sync="testStateLoading.isTesting"
        :show-title="false"
        :right-btn-visible="false"
        :left-btn-visible="false"
        :content-customer-style="{ padding: '35rpx 0' }"
        :closeOnClickOverlay="false"
      >
        <div
          style="color: #13131380"
          v-if="testStateLoading.testingState === 'testing'"
          class="flex-align-center"
        >
          <u-loading-icon :color="themeColor"></u-loading-icon>
          <div class="marginLeft-23">检验中，请稍等...</div>
        </div>
        <div
          style="color: #13131380"
          class="flex-align-center"
          v-if="testStateLoading.testingState === 'success'"
        >
          <u-icon name="checkmark-circle-fill" :color="themeColor" size="28" />
          <div class="marginLeft-23">校验成功</div>
        </div>
      </modal>
    </div>
    <error-modal ref="errorModalRef" />
  </auth-page>
</template>

<script>
import { mapState } from "vuex";
import { getUrlQuery } from "@/utils/format";
import {
  editWifiConfig,
  geiWiFiQrcodeScan,
  wifiBind,
} from "@/service/api/sp-store/wifi";
import {
  BIND_PAGE_TYPE,
  EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI,
  EVENT_TRACK_TYPE_OF_BUSINESS_FOR_WIFI,
  SCOPE,
} from "@/pages/sp-store/const/wifi";
import errorModal from "../../components/errorModal";
import { mixinAuth } from "@/mixin/sp-common/mixin-auth";
import baseMixin from "@/pages/sp-store/mixin/bind-wifi/base";

export default {
  mixins: [mixinAuth, baseMixin],
  components: { errorModal },
  data() {
    return {
      BIND_PAGE_TYPE,
      pageType: BIND_PAGE_TYPE.BINGING,
      params: {
        wifiName: "",
        password: "",
        pubDomainBusinessId: "",
        pubDomainShopId: "",
        wifiCode: "",
        phone: "",
        storeNo: "",
        pubDomainShopName: "",
      },
      btnCustomStyle: {
        width: "calc(686rpx - 54rpx)",
        backgroundColor: "#ffffff",
        padding: "24rpx 27rpx",
        margin: "0 auto",
        borderRadius: "15rpx",
        fontSize: "28rpx",
      },
      rules: {
        wifiName: {
          type: "string",
          required: true,
          message: "请输入WiFi账号",
          trigger: ["blur", "change"],
        },
        password: {
          type: "string",
          required: true,
          message: "请输入WiFi密码",
          trigger: ["blur", "change"],
        },
      },
      isShowBindBusiness: false,
      isShowTestWiFiFail: false,
      businessList: [],
      bindBusinessTitle: "",
      tempShopId: "",
      options: {},
      urlQuery: {},
      testStateLoading: {
        isTesting: false,
        testingState: "testing", //testing,success
      },
      wifiEnabled: true, //WiFi开关
      btnLoading: false,
    };
  },
  computed: {
    ...mapState("sp-common/base", ["themeColor"]),
    ...mapState("sp-common/auth", ["app_token"]),
    disabledInput({ params }) {
      return !(params?.wifiName && params?.password);
    },
    typeOfBusiness({ pageType }) {
      return pageType === 0
        ? EVENT_TRACK_TYPE_OF_BUSINESS_FOR_WIFI.BIND
        : EVENT_TRACK_TYPE_OF_BUSINESS_FOR_WIFI.EDIT;
    },
    eventTrackMustInfo({ typeOfBusiness, params }) {
      return {
        sign: "wifi",
        opType: typeOfBusiness,
        wifiName: params?.wifiName,
        wifiPassword: params?.password,
        pubDomainShopName: params?.pubDomainShopName,
        pubDomainShopId: params?.pubDomainShopId,
        pubDomainBusinessId: params?.pubDomainBusinessId,
        deviceNo: params?.wifiCode,
      };
    },
  },
  onLoad(options) {
    console.log("onLoad参数options", options);
    this.options = options;
    this.$nextTick(() => {
      this.innit(); //有token的情况下初始化
    });
  },
  onShow() {
    this.options = this.$Route.query;
    console.log("onShow当前路由参数===", this.options);
    // this.$nextTick(() => {
    //   this.innit(); //有token的情况下初始化
    // });
    const systemInfo = uni.getSystemInfoSync();
    this.wifiEnabled = systemInfo?.wifiEnabled;
    if (!systemInfo?.wifiEnabled) {
      uni.showToast({
        icon: "error",
        title: "请打开手机WiFi",
      });
      return;
    }
  },

  watch: {
    app_token: {
      handler(val) {
        if (val) {
          uni.$u.debounce(this.innit, 1000);
          this.$store.dispatch("sp-common/base/getUserWxConfig");
          // this.innit(); //有token的情况下初始化
        }
      },
      deep: true,
      // immediate: true,
    },
    tempShopId: {
      handler(val) {
        const shop = this.businessList.filter((v) => v.id === val)[0];
        this.params.pubDomainShopId = val;
        this.params.pubDomainBusinessId = shop?.pubDomainBusinessId;
        this.params.storeNo = shop?.storeNo;
        this.params.pubDomainShopName = shop?.shopName;
        console.log("更新", this.params);
      },
    },
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.addWifiFormRef.setRules(this.rules);
  },
  methods: {
    innit() {
      const options = this.options;
      if (options) {
        if (options?.q) {
          //从WiFi码进来的
          const q = decodeURIComponent(options.q); // 获取到二维码原始链接内容
          const q1 = decodeURIComponent(q); // 获取到二维码原始链接内容
          const query = getUrlQuery(q1);
          this.urlQuery = query;
          this.options.code = query.code;
          this.params.wifiCode = query.code;
          this.innitWifiData();
        }
        if (options?.pageType) {
          this.pageType = options.pageType;
        }
        if (Number(options?.pageType) === BIND_PAGE_TYPE.EDIT && options?.id) {
          //从我的WiFi列表进来的
          this.fetchWiFiDetail();
        }

        //假如这个码被设置过，需要跳转到我的WiFi页面
        // this.$Router.push({
        //   path: "pages/sp-store/pages/my-bind-wifi-list/index",
        // });
      }
    },
    async innitWifiData() {
      if (!this.urlQuery?.code) return;
      const res = await geiWiFiQrcodeScan({
        deviceNo: this.urlQuery.code,
      });
      console.log("初始化码牌", res, this.urlQuery);
      if (res) {
        const { isBind, code, wifiConfigVo, message } = res;
        this.isBind = isBind;
        this.pageType = !isBind ? BIND_PAGE_TYPE.BINGING : BIND_PAGE_TYPE.EDIT;
        if (isBind) {
          if (code === SCOPE.BIND_BY_OTHER_USER) {
            // uni.showToast({
            //   icon: "none",
            //   title: message,
            // });
            uni.redirectTo({
              url: `pages/sp-store/pages/link-wifi/index?name=${wifiConfigVo?.wifiName}&password=${wifiConfigVo?.password}&deviceNo=${wifiConfigVo.wifiCode}`,
            });
            // setTimeout(()=>{})
          }
          if (code === SCOPE.BIND_BY_MY_SELF) {
            this.params = {
              ...wifiConfigVo,
            };
          }
        } else {
          if (!this.testStateLoading.isTesting) {
            this.params = {
              wifiName: this.params.wifiName,
              password: this.params.password,
              pubDomainBusinessId: "",
              pubDomainShopId: "",
              wifiCode: this.params.wifiCode,
              phone: "",
              storeNo: "",
            };
          }
        }
      }
    },
    async handleSubmitWiFi() {
      if (this.btnLoading) return;
      this.btnLoading = true;
      const systemInfo = uni.getSystemInfoSync();
      if (!systemInfo?.wifiEnabled) {
        this.handleEventTrack({
          ...this.params,
          ...this.eventTrackMustInfo,
          status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_FAIL,
          failReason: "点击保存提交WiFi信息，" + "未手机WiFi",
        }); //数据埋点
        uni.showToast({
          icon: "error",
          title: "请打开手机WiFi",
        });
        return;
      }
      this.params.wifiCode = this.options.code;
      console.log(
        "二维码设置中",
        this.pageType === BIND_PAGE_TYPE.BINGING ? "新增" : "编辑",
        this.params
      );
      //新增绑定的时候
      if (this.pageType === BIND_PAGE_TYPE.BINGING) {
        try {
          const res = await wifiBind({ ...this.params });
          console.log("二维码设置结果===", res);
          this.btnLoading = false;
          if (res) {
            this.handleEventTrack({
              ...res,
              ...this.eventTrackMustInfo,
              status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.BUSINESS_SUCCESS,
              failReason: "点击保存提交WiFi信息，" + "绑定成功",
            }); //数据埋点
            this.pageType = BIND_PAGE_TYPE.EDIT;
            this.tempShopId = "";
            this.bindBusinessTitle = "";
            this.businessList = [];
            //获取WiFi信息-重新插入到数据里
            this.$refs.errorModalRef.open("保存成功");
            await this.innitWifiData();
            // uni.showToast({
            //   icon: "success",
            //   title: "设置成功",
            //   success: () => {},
            // });
          }
        } catch (err) {
          this.btnLoading = false;
          this.handleEventTrack({
            ...err,
            ...this.eventTrackMustInfo,
            status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.BUSINESS_FAIL,
            failReason: "点击保存提交WiFi信息失败，" + JSON.stringify(err),
          }); //数据埋点
          if (err?.code === -2) {
            this.$refs.errorModalRef.open(" 保存失败，此WiFi码已被他人绑定");
          } else {
            if (err?.msg) {
              this.$refs.errorModalRef.open(err?.msg || JSON.stringify(err));
            }
          }
          console.log("提交错误", err);
        }
        return;
      }
      //保存已有WiFi的时候
      if (this.pageType === BIND_PAGE_TYPE.EDIT) {
        const res = await editWifiConfig({ ...this.params }).catch((err) => {
          console.log("保存已有WiFi的时候错误", err);
          this.btnLoading = false;
          this.handleEventTrack({
            ...res,
            ...this.eventTrackMustInfo,
            status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.BUSINESS_FAIL,
            failReason: "点击保存已有WiFi信息失败，" + JSON.stringify(err),
          }); //数据埋点
          if (err?.code === -2) {
            this.$refs.errorModalRef.open(" 保存失败，此WiFi码已被他人绑定");
          } else {
            if (err?.msg) {
              this.$refs.errorModalRef.open(err?.msg || JSON.stringify(err));
            }
          }
        });
        if (res) {
          this.btnLoading = false;
          this.handleEventTrack({
            ...res,
            ...this.eventTrackMustInfo,
            status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.BUSINESS_SUCCESS,
            failReason: "点击保存已有WiFi信息成功，" + "保存成功",
          }); //数据埋点
          this.$refs.errorModalRef.open("保存成功");
          await this.innitWifiData();
        }
      }
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  width: 100vw;
  margin: 0 auto;
  padding-top: 20rpx;
  background-color: #f9f9f9;
  //background-color: #888888;
  min-height: 100vh;
}
.fix-position {
  position: fixed;
  left: 0;
  bottom: calc(env(safe-area-inset-bottom) + 40rpx);
}
.footer {
  width: calc(100vw - 40rpx);
  padding: 10rpx 20rpx;
  border-top: 1rpx solid whitesmoke;
  .myWifi {
    margin-right: 30rpx;
  }
  .default-button {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    font-size: 30rpx;
  }
}
.business-container {
  padding: 0 53rpx;
  text-align: left;
  .font-red {
    color: red;
  }
  .text {
    margin: 21rpx 0;
    text-align: left;
    font-size: 26rpx;
  }
  .fail {
    font-size: 29rpx;
  }
}
.tips {
  background-color: #f9f9f9;
  line-height: 36rpx;
  opacity: 0.8;
  div {
    font-size: 28rpx;
    margin-top: 18rpx;
  }
}
.maxInput {
  font-size: 22rpx;
  color: #888888;
}
</style>
